package com.chuanyang.driverh.mainmy;


import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.chuanyang.driverh.BaseApplication;
import com.chuanyang.driverh.R;
import com.chuanyang.driverh.amap.LocationEntity;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.responseresult.DriverInfoData;
import com.chuanyang.driverh.responseresult.LogisticsCompanyData;
import com.chuanyang.driverh.responseresult.Result;
import com.chuanyang.driverh.utils.ActivityUtil;
import com.chuanyang.driverh.utils.BitmapUtil;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PermissoinUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.StringUtil;
import com.chuanyang.driverh.utils.camera.CameraUtils;
import com.chuanyang.driverh.utils.camera.DialogPhotoChooseView;
import com.chuanyang.driverh.utils.camera.DropDownList;
import com.chuanyang.driverh.utils.camera.SelectPictureListener;
import com.chuanyang.driverh.utils.camera.TakePictureListener;
import com.chuanyang.driverh.utils.eventbus.AddAddrEvent;
import com.chuanyang.driverh.utils.eventbus.RefleshDriverInfoEvent;
import com.chuanyang.driverh.utils.eventbus.SelectCompanyEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 *
 */

public class UserInfoActivity extends BaseTitleActivity {
    private LinearLayout ll_userinfo_icon;//头像
    private ImageView iv_icon;
    private EditText et_userinfo_name;//姓名
    private RadioButton sex_man;
    private RadioButton sex_female;
    private EditText et_phone;//手机
    private EditText et_identifycard;//身份证
//    private EditText et_bankcard;
    private TextView tv_address;
    private TextView tv_linkcompany;
    private Button but_modify;
    private DriverInfoData driverinfo;
    private LogisticsCompanyData logisticsCompanyData;
    @Override
    protected int getContentResId() {
        return R.layout.my_act_userinfo;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ll_userinfo_icon = (LinearLayout) findViewById(R.id.ll_userinfo_icon);
        iv_icon = (ImageView) findViewById(R.id.iv_userinfo_icon);
        et_userinfo_name = (EditText) findViewById(R.id.et_userinfo_name);
        sex_man=(RadioButton)findViewById(R.id.sex_man);
        sex_female=(RadioButton)findViewById(R.id.sex_female);
        et_phone = (EditText) findViewById(R.id.et_userinfo_phone);//电话号码
        et_identifycard = (EditText) findViewById(R.id.et_userinfo_identifycard);//身份证
//        et_bankcard = (EditText) findViewById(R.id.et_userinfo_bankcard);//银行卡
        tv_address = (TextView) findViewById(R.id.tv_userinfo_address);//地址
        tv_linkcompany = (TextView) findViewById(R.id.tv_userinfo_linkcompany);//挂靠公司
        but_modify = (Button) findViewById(R.id.but_modify);//修改个人信息
    }

    @Override
    protected void initData() {
        setBackImg();
        getTitleTextView().setText("个人信息");
        fillView();
    }

    @Override
    protected void initListener() {
        ll_userinfo_icon.setOnClickListener(this);
        tv_address.setOnClickListener(this);
        tv_linkcompany.setOnClickListener(this);
        but_modify.setOnClickListener(this);
    }

    private void fillView() {
        driverinfo= BaseApplication.getInstance().getDriverInfo();
        if (driverinfo==null){
            return;
        }
        BitmapUtil.showImgForNetPath(driverinfo.getUserImage(),iv_icon);
        et_phone.setText(driverinfo.getPhone());
        if (!StringUtil.isBlank(driverinfo.getUsername())) {
            et_userinfo_name.setText(driverinfo.getUsername());
        }
        if (!StringUtil.isBlank(driverinfo.getUserSex())) {
            if (driverinfo.getUserSex().equals("男")) {
                sex_man.setChecked(true);
                sex_female.setChecked(false);
            } else {
                sex_man.setChecked(false);
                sex_female.setChecked(true);
            }
        }
        if (!StringUtil.isBlank(driverinfo.getUserAddr())) {
            tv_address.setText(driverinfo.getUserAddr());
        }
        if (!StringUtil.isBlank(driverinfo.getiDNumber())) {
            et_identifycard.setText(driverinfo.getiDNumber());

        }
        if (!StringUtil.isBlank(driverinfo.getLogisticsCompanyName())) {
            tv_linkcompany.setText(driverinfo.getLogisticsCompanyName());
        }
    }


    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_userinfo_icon:
                checkPermission();
                break;
            case R.id.tv_userinfo_address:
                ActivityUtil.startActivity(activityContext,new Intent(activityContext,AddAddrActivity.class).putExtra("type",1));
                break;
            case R.id.tv_userinfo_linkcompany:
                ActivityUtil.startActivity(activityContext,TranslateCompanyActivity.class);
                break;
            case R.id.but_modify:
                checkInput();
                break;
        }
    }
    private void checkPermission() {
            String[] perms = {Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (PermissoinUtil.checkAndRequestPermissions(activityContext,perms)){
                DialogPhotoChooseView mChooseView = new DialogPhotoChooseView(this).setCameraListener(new TakePictureListener(this)).setAlbumListener(new SelectPictureListener(this));
                DropDownList.showDialog(this, mChooseView);
            }else{
                PrintUtil.toast(activityContext,"请给应用相应的权限");
            }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CameraUtils.REQUEST_CODE_TAKE_PICTURE) {//直接拍照
                File photo = BitmapUtil.compressImage(CameraUtils.mCurrentPhotoPath, this);
                uploadAvatar(photo);

            }
            if (requestCode == CameraUtils.REQUEST_CODE_SELECT_PICTURE && data != null) {//从相册中选择
                if (data.getData() != null) {
                    File photo = BitmapUtil.compressImage(CameraUtils.getPath(this, data.getData()), this);
                  if (photo!=null) uploadAvatar(photo);
                }
            }
        }
    }

    private void uploadAvatar(final File file) {

        DialogUtil.showLoadingDialog(activityContext,"更改头像...");
        MyHttpUtil.changeUserImage(activityContext,file, new MyCallback<Result>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    PrintUtil.toast(activityContext,"成功修改头像");
//                    BitmapUtil.showLocalImg(file.getAbsolutePath(),iv_icon);
                    BaseApplication.getInstance().getDriverInfoFromNet();

                    file.delete();
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });

    }


    private void checkInput() {
        String name=et_userinfo_name.getText().toString().trim();
        String phone=et_phone.getText().toString().trim();
        String idNum=et_identifycard.getText().toString().trim();
        String addr=tv_address.getText().toString().trim();
        if (StringUtil.isBlank(name)){
            PrintUtil.toast(activityContext,"请填写姓名");
            return;
        }else if(!StringUtil.isPhoneNumber(phone)){
            PrintUtil.toast(activityContext,"请填写正确的手机号");
            return;
        }else if(!StringUtil.isCard(idNum)){
            PrintUtil.toast(activityContext,"请填写正确的身份证号");
            return;
        }else if(StringUtil.isBlank(addr)){
            PrintUtil.toast(activityContext,"请选择地址");
            return;
        }
        updateUser(name,phone,idNum,addr);
    }

    private void updateUser(String name,String phone,String idNum,String addr) {
        DialogUtil.showLoadingDialog(activityContext,"修改信息...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("username", name);
        params.put("phoneCall",phone);
        params.put("iDNumber", idNum);
        params.put("userAddr", addr);
        params.put("userSex", sex_man.isChecked()?"男":"女");
        if (logisticsCompanyData != null) {
            params.put("companyId", logisticsCompanyData.getLogisticsCompanyId() + "");
        }
        params.put("userId", SharedPrefUtil.getUserId());

        MyHttpUtil.updateUser(activityContext,params, new MyCallback<Result>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    PrintUtil.toast(activityContext,"用户信息修改成功");
                    BaseApplication.getInstance().getDriverInfoFromNet();//刷新数据
                    onBackPressed();
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });
    }

//选取公司后
    public void onEventMainThread(SelectCompanyEvent event) {
        if (event.getData() != null) {
            logisticsCompanyData = event.getData();
            tv_linkcompany.setText(logisticsCompanyData.getLogisticsCompanyName());
        }
    }
    //选取地址后
    public void onEventMainThread(AddAddrEvent event) {
        if (event.getType()==1 && event.getEntity() != null) {
            LocationEntity entity = event.getEntity();
            tv_address.setText(entity.getCity()+","+entity.getBuilding()+","+entity.getAddress());
        }
    }

    public void onEventMainThread(RefleshDriverInfoEvent event) {
        if (event.isRefleshDriverInfo()){
            driverinfo= BaseApplication.getInstance().getDriverInfo();
            if (driverinfo==null){
                return;
            }
            BitmapUtil.showImgForNetPath(driverinfo.getUserImage(),iv_icon);
        }
    }

}
